<template>
  <div class="app-container">
    <div class="filter-container">
      <el-date-picker
        v-model="dateRange"
        value-format="yyyy-MM-dd"
        type="daterange"
        range-separator="~"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :editable="false"
        class="filter-item"
        @change="changeDate"
      />
      <el-input v-model="listQuery.plateNumber" placeholder="车牌号" class="filter-item" clearable style="width: 200px;" />
      <el-select v-model="listQuery.exchange" placeholder="兑现状态" clearable class="filter-item" style="width: 120px;">
        <el-option v-for="item in exchangeOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      <el-button v-if="type == 0" v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
      <!--      <el-button v-if="type == 0" v-waves class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">新增白名单</el-button> -->
    </div>

    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;">
      <el-table-column label="车牌号" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.plateNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.effectiveDate | parseTime('{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="优先次数" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.discountNum }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="过期时间" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.expireTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="白名单原因" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.reasonType | reasonTypeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="兑现状态" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.exchange | exchangeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="兑现时间" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.exchangeDate | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.createUser }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="type == 0" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">
          <!--          <el-button size="mini" icon="el-icon-edit" type="primary" @click="handleEdit(row)">编辑</el-button> -->
          <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="getList" />
    <div v-if="dialogAddFormVisible">
      <el-dialog title="新增白名单" :visible.sync="dialogAddFormVisible" :append-to-body="true" :close-on-click-modal="false" :destroy-on-close="true">
        <WhitelistAddForm ref="whitelistAddForm" :length="total" @close="whitelistAddFormClose" @cancelClose="cancelClose(arguments)" />
      </el-dialog>
    </div>
    <div v-if="dialogEditFormVisible">
      <el-drawer :visible.sync="dialogEditFormVisible" direction="rtl" size="85%" :append-to-body="true" :destroy-on-close="true" :wrapper-closable="false" :with-header="false">
        <WhitelistAddForm :id="editId" ref="whitelistEditForm" @cancelClose="cancelClose(arguments)" />
      </el-drawer>
    </div>
  </div>
</template>

<script>
import { getWhitelist, deleteWhitelist } from '@/api/whitelist';
import waves from '@/directive/waves';
import Pagination from '@/components/Pagination';
import WhitelistAddForm from '@/views/services/whitelistAdd.vue';
import { parseTime } from '@/utils';

var that;

export default {
  name: 'Whitelist',
  components: { Pagination, WhitelistAddForm },
  directives: { waves },
  filters: {
    reasonTypeFilter(item) {
      const reasonTypeKeyValue = that.reasonTypeOptions.reduce((acc, cur) => {
        acc[cur.key] = cur.label;
        return acc;
      }, {});
      return reasonTypeKeyValue[item];
    },
    exchangeFilter(item) {
      const exchangeKeyValue = that.exchangeOptions.reduce((acc, cur) => {
        acc[cur.key] = cur.label;
        return acc;
      }, {});
      return exchangeKeyValue[item];
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      downloadLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        plateNumber: '',
        exchange: null,
        beginTime: '',
        endTime: ''
      },
      dateRange: [],
      reasonTypeOptions: [{ label: '订单原因', key: 1 }, { label: '摄像头未拍到离场记录', key: 2 }, { label: '其他', key: 3 }],
      exchangeOptions: [{ label: '未兑现', key: 0 }, { label: '已兑现', key: 1 }, { label: '已过期', key: 2 }],
      dialogAddFormVisible: false,
      dialogEditFormVisible: false,
      editId: 0,
      type: null
    };
  },
  created() {
    that = this;
    const { params } = this.$route
    Object.keys(params).forEach(key => {
      this.type = params[key].split(':')[1];
    });
    this.dateRange.push(parseTime(new Date(), '{y}-{m}-{d}'));
    this.dateRange.push(parseTime(new Date(), '{y}-{m}-{d}'));
    this.listQuery.beginTime = this.dateRange[0] + ' 00:00:00';
    this.listQuery.endTime = this.dateRange[1] + ' 23:59:59';
    this.getList();
  },
  methods: {
    async getList() {
      this.listLoading = true;
      await getWhitelist(this.listQuery).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    async handleSearch() {
      this.getList();
    },
    changeDate(val) {
      if (val) {
        this.listQuery.beginTime = val[0] + ' 00:00:00';
        this.listQuery.endTime = val[1] + ' 23:59:59';
      } else {
        this.listQuery.beginTime = null;
        this.listQuery.endTime = null;
      }
    },
    handleCreate() {
      this.dialogAddFormVisible = true;
    },
    async handleDelete(row) {
      await this.$confirm('确定要此条数据吗？', '刪除操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          this.listLoading = true;
          await deleteWhitelist(row.id).then(res => {
            this.listLoading = false;
            if (res.msg !== 'OK') {
              this.$message.error(res.msg);
              return;
            }
            this.getList();
            this.$message.success('删除成功');
          });
        })
        .catch(() => {});
    },
    handleEdit(row) {
      this.editId = row.id;
      this.dialogEditFormVisible = true;
    },
    blacklistAddFormClose() {
      this.dialogAddFormVisible = false;
    },
    cancelClose(data) {
      if (data[1] === 'add') {
        this.dialogAddFormVisible = false;
      } else {
        this.dialogEditFormVisible = false;
      }
      if (data[0]) {
        if (data[1] === 'add') {
          this.listQuery.pageNum = 1;
          this.listQuery.pageSize = 10;
          this.listQuery.plateNumber = '';
          this.listQuery.beginTime = null;
          this.listQuery.endTime = null;
        }
        this.getList();
      }
    },
    async handleDownload() {
      if (this.total === 0) {
        this.$message.error('暂无数据');
        return;
      }
      this.downloadLoading = true;
      this.listQuery.pageSize = this.total;
      await getWhitelist(this.listQuery).then(response => {
        this.listQuery.pageSize = 10;
        if (response.data.total === 0) {
          this.$message.error('暂无数据，请重新刷新页面');
          return;
        }
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['车牌号', '开始时间', '过期时间', '白名单原因', '兑现状态', '兑现时间', '创建人', '创建时间'];
          const filterVal = ['plateNumber', 'effectiveDate', 'expireTime', 'reasonType', 'exchange', 'exchangeDate', 'createTime'];
          const data = this.formatJson(response.data.list, filterVal);
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '白名单'
          });
          this.downloadLoading = false;
          this.$message({
            message: '白名单导出成功',
            type: 'success'
          });
        });
      });
    },
    formatJson(list, filterVal) {
      const reasonTypeFilter = this.$options.filters['reasonTypeFilter'];
      const exchangeFilter = this.$options.filters['exchangeFilter'];
      return list.map(v =>
        filterVal.map(j => {
          if (j === 'effectiveDate' || j === 'expireTime' || j === 'exchangeDate' || j === 'createTime') {
            return parseTime(v[j], '{y}-{m}-{d}');
          } else if (j === 'reasonType') {
            return reasonTypeFilter(v[j]);
          } else if (j === 'exchange') {
            return exchangeFilter(v[j]);
          } else {
            return v[j];
          }
        })
      );
    }
  }
};
</script>
